package com.lixh.sdk.base.http

import android.content.Context
import com.lixh.sdk.base.util.isNetworkAvailable

import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import javax.net.ssl.*

object ClientHelper {


    //无网络下强制使用缓存，无论缓存是否过期,此时该请求实际上不会被发送出去。
    //有网络情况下，根据请求接口的设置
    //服务端设置了缓存策略，则使用服务端缓存策略
    //服务端未设置缓存策略，则客户端自行设置
    //无网络
    //拦截器
    class AutoCacheInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            if (!isNetworkAvailable()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE)
                    .build()
            }

            val response = chain.proceed(request)
            if (!isNetworkAvailable()) {
                val cacheControl = request.cacheControl.toString()
                cacheControl.let {
                    response.newBuilder().header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build()
                }

            } else {
                response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=3600000")
                    .removeHeader("Pragma")
                    .build()
            }
            return response
        }
    }

    //证书全部信任
    val trustManager: X509TrustManager = object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<X509Certificate?>?, authType: String?) {
        }

        @Throws(CertificateException::class)
        override fun checkServerTrusted(chain: Array<X509Certificate?>?, authType: String?) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOfNulls(0)
        }
    }

    val sslSocketFactory: SSLSocketFactory
        get() {
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, arrayOf<TrustManager>(trustManager), SecureRandom())
            return sslContext.socketFactory
        }


    internal fun getSSLSocketFactory(context: Context?, certificates: IntArray): SSLSocketFactory? {

        if (context == null) {
            throw NullPointerException("context == null")
        }

        //CertificateFactory用来证书生成
        val certificateFactory: CertificateFactory
        try {
            certificateFactory = CertificateFactory.getInstance("X.509")
            //Create a KeyStore containing our trusted CAs
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            keyStore.load(null, null)

            for (i in certificates.indices) {
                //读取证书文件
                val `is` = context.resources.openRawResource(certificates[i])
                keyStore.setCertificateEntry(
                    i.toString(),
                    certificateFactory.generateCertificate(`is`)
                )

                `is`.close()
            }
            //Create a TrustManager that trusts the CAs in our keyStore
            val trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(keyStore)

            //Create an SSLContext that uses our TrustManager
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            return sslContext.socketFactory

        } catch (_: Exception) {

        }

        return null
    }

    internal fun getHostnameVerifier(hostUrls: Array<String>): HostnameVerifier {

        return HostnameVerifier { hostname, session ->
            true
        }


    }


}